<?php

require_once('json.inc.php');

$page = $_GET['page']; // get the requested page 
$limit = $_GET['rows']; // get how many rows we want to have into the grid 
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort 
$sord = $_GET['sord']; // get the direction 

require('../dbconnect.inc.php');

$rs = $dbh->query('select count(*) from users');

if ($rec = $rs->fetchAll(PDO::FETCH_COLUMN, 0))
{
	$count = $rec[0];
}
else
{
	$count = 0;
}

if( $count > 0 ) 
{ 
	$total_pages = ceil($count/$limit); 
} 
else 
{ 
	$total_pages = 0; 
} 

if ($page > $total_pages) 
	$page=$total_pages;


$start = $limit * $page - $limit; // do not put $limit*($page - 1) 

if ($start < 0) 
	$start = 0;

$sth = $dbh->prepare('select * from users order by ' . $sidx . ' ' . $sord  . ' limit :start,:limit');

$sth->bindParam(':start', intval($start), PDO::PARAM_INT);
$sth->bindParam(':limit', intval($limit), PDO::PARAM_INT);

$sth->execute();

$responce->page = $page; 
$responce->total = $total_pages; 
$responce->records = $count; 

$alldb = $sth->fetchAll(PDO::FETCH_ASSOC);

foreach( $alldb as $key => $val)
{
	$sth2 = $dbh->prepare('select g_id from users_groups where u_id=:u_id');
	$sth2->execute(array(':u_id'=>$val['u_id']));

	$g_list = '';
	$alldb2 = $sth2->fetchAll(PDO::FETCH_COLUMN, 0);

	foreach( $alldb2 as $key2 => $val2)
	{
		if (empty($g_list))
		{
			$g_list .= $val2['g_id'];
		}
		else	
		{
			$g_list .= ',' . $val2['g_id'];
		}
	}

	$responce->rows[$key]['id'] = $val['u_id'];
	$responce->rows[$key]['cell'] = array( $val['u_login'], $val['u_name'],'******', '******', (($val['u_p_admin'] == 1) ? 'Да' : 'Нет'),(($val['u_p_edit'] == 1) ? 'Да' : 'Нет'), $g_list);
}

echo json_encode($responce);

?>
